# _*_ coding: utf-8 _*_
__author__ = 'Haoge'
from django.views.generic import TemplateView, ListView, View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView, View
from django.shortcuts import render,render_to_response,HttpResponse
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from resources.models import ServerGroup,NewServer
from confs.views import get_pagerange
from django.core import serializers
import json
from confs.Log import logger

# 资产组
class GroupListView(LoginRequiredMixin, ListView):
	def get(self,request):
		template_name = 'groups/group_list.html'
		model = ServerGroup
		paginate_by = 10
		ordering = 'id'
		return render_to_response('groups/group_list.html', locals())

class GroupAPIJsonView(LoginRequiredMixin, ListView):
	def get(self,request):
		jsondata = {
			"code": 0,
			"msg": "",
			"count": 10,
			"data": [
			]
		}
		groups = ServerGroup.objects.all()
		for s in groups:
			hosts = s.servergroup.all()
			hosts = ','.join([m.hostname for m in hosts ])
			m = {"id": s.id,"groupname":s.name,"hosts":hosts,"utime":s.utime}
			jsondata["data"].append(m)

		return JsonResponse(jsondata)

class AddGroupView(LoginRequiredMixin, View):

	template_name = 'servers/add_group.html'

	def get(self, request):

		newservers = [ {"value":m.id,"name":m.hostname} for m in  NewServer.objects.all()]
		jsondata = {"newservers":newservers}

		return JsonResponse(jsondata)

class GroupCreateView(LoginRequiredMixin, TemplateView):
	template_name = 'groups/group_create.html'

	def get(self, request):
		user = request.user.username
		obj_groups = ServerGroup.objects.all()
		obj_newserver = NewServer.objects.all()
		return render_to_response('groups/group_create.html', locals())

	def post(self,request):

		name = request.POST.get('name')
		info = request.POST.get('info')
		memberslist = request.POST.get('select','')
		memberslist = memberslist.split(',')

		if name  in [ g.name for g in ServerGroup.objects.all()]:
			ret = {'status': 1}
			ret['msg'] = '资产组名%s已存在'%name
			return JsonResponse(ret)

		ServerGroup.objects.create(name=name,info=info)

		if memberslist != ['']:
			gp = ServerGroup.objects.get(name=name)
			for server_id in memberslist:
				lp = NewServer.objects.get(id=server_id)
				lp.server_group = gp
				lp.save()

		ret = {'status': 0}
		ret['msg'] = '资产组创建成功'
		return JsonResponse(ret)



class GroupEditView(LoginRequiredMixin, TemplateView):
	template_name = 'groups/group_edit.html'

	def get(self, request):
		id = request.GET.get('id')
		group = ServerGroup.objects.get(id=id)
		servers = NewServer.objects.all()
		data_list = []
		hostid_list  = [x.id for x in group.servergroup.all()]

		for s in servers:
			if s.id in hostid_list:
				data_list.append({"name":s.hostname,"value":s.id,"selected":True})
			else:
				data_list.append({"name": s.hostname, "value": s.id})
		jsondata = {"id": group.id, "name": group.name, "data_list": data_list, "info": group.info}

		return JsonResponse(jsondata)

	def post(self,request):
		id = request.POST.get('id')
		name = request.POST.get('name')
		info = request.POST.get('info','')
		members = request.POST.get('select')
		memberslist = members.split(',')
		ServerGroup.objects.filter(id=id).update(name=name,info=info)
		lgp = ServerGroup.objects.get(id=id)
		# lgp.gl.clear()

		# 多对多添加
		lp = NewServer.objects.filter(id__in=memberslist)
		lgp.servergroup.set(lp)
		lgp.save()
		return HttpResponseRedirect('/resources/group/list/')


class GroupDeleteView(LoginRequiredMixin, TemplateView):

	def post(self,request):
		ret = {'status': 0}
		servergroup_id = request.POST.get('servergroup_id')
		lp = ServerGroup.objects.get(id=servergroup_id)
		lp.delete()
		ret['msg'] = '资产组删除成功'
		return JsonResponse(ret)